<!--  -->

<template>
    <view>

        <u-grid :border="false" col="2">
            <u-grid-item v-for="o in DataList" :key="o" style="text-align: center;">

                <u--image :showLoading="true" :src="'https://ztapp-1304966785.cos.ap-nanjing.myqcloud.com/' + o.Key"
                    :lazy-load="true" :fade="true" duration="450" mode="aspectFit" width="45vw"
                    @click="ActionSheet(o.Key)"></u--image>

            </u-grid-item>

        </u-grid>


        <movable-area class="movable-area">
            <movable-view class="movable-view" :x="x" :y="y" direction="all">
                <image src="https://ztapp-1304966785.cos.ap-nanjing.myqcloud.com/%E4%B8%8A%E4%BC%A0-%E5%9C%86-F.png"
                    @click="upload">
                </image>
            </movable-view>
        </movable-area>

    </view>
</template>

<script>
import COS from './lib/cos-wx-sdk-v5.js'
const cos = new COS({
    SecretId: 'AKID2uZ3KNC3g5FBsLZYKsBGWYKrAF6i6E8n',
    SecretKey: 'UAfw0pRwEI8kHbmjSx64qRq55sQnz50l',
});
export default {
    data() {
        return {
            user: {},
            DataList: [],
            x: 20,		//x坐标
            y: 720,		//y坐标
            urls: []

        };
    },

    components: {},

    computed: {},

    mounted() {
        this.user = uni.getStorageSync('user');
        const systemInfo = uni.getSystemInfoSync();
        this.y = systemInfo.windowHeight - 100;
        this.load();

    },

    created() { },

    methods: {
        ActionSheet(key) {
            let that = this;
            uni.showActionSheet({
                itemList: ['预览', '下载', '删除'],

                success: function (res) {
                    console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
                    if (res.tapIndex == 2) {
                        that.deleteFileToTencentClound(key)
                    }
                    else if (res.tapIndex == 1) {
                        that.downloadToTencentClound(key)
                    }
                    else if (res.tapIndex == 0) {
                        that.previewImage('https://ztapp-1304966785.cos.ap-nanjing.myqcloud.com/' + key)
                    }
                    that.load();
                },
                fail: function (res) {
                    console.log(res.errMsg);
                }
            });

        },
        load() {
            let that = this;
            cos.getBucket({
                Bucket: 'ztapp-1304966785',
                Region: 'ap-nanjing',
                Prefix: this.user.openid + '/',           /* Prefix表示列出的object的key以prefix开始，非必须 */
            }, function (err, data) {
                console.log(err || data.Contents);

                that.DataList = data.Contents;
                that.urls = [];
                for (let key in that.DataList) {
                    if (that.DataList.hasOwnProperty(key)) {

                        that.urls.push('https://ztapp-1304966785.cos.ap-nanjing.myqcloud.com/' + that.DataList[key].Key)
                    }
                }

            });

        },
        upload() {
            let that = this;
            uni.chooseImage({
                count: 1, //默认9
                sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album'], //从相册选择
                success: function (res) {
                    console.log('res', res)
                    let filePath = res.tempFiles[0].path;
                    let filename = filePath.substr(filePath.lastIndexOf('/') + 1);
                    that.uploadFileToTencentClound(filename, filePath).then((res) => {
                        that.load();
                    })
                }
            });

        },
        previewImage(currentUrl) {
            uni.previewImage({
                current: currentUrl, // 当前显示的图片链接
                urls: this.urls // 需要预览的图片链接列表
            });
        },
        deleteFileToTencentClound(Key) {
            console.log('deleteFileToTencentClound', Key)
            return new Promise((resolve, reject) => {
                cos.deleteObject({
                    Bucket: 'ztapp-1304966785',
                    Region: 'ap-nanjing',
                    Prefix: this.user.openid + '/',
                    Key: Key,
                }, function (err, data) {
                    console.log(err || data);
                    resolve(data)
                });
            })
        },
        downloadToTencentClound(Key) {
            cos.getObjectUrl({
                Bucket: 'ztapp-1304966785',
                Region: 'ap-nanjing',
                Key: Key,  /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
                Sign: true
            }, function (err, data) {
                if (err) return console.log(err);
                uni.showLoading({
                    title: '下载中'
                });
                uni.downloadFile({
                    url: data.Url, //仅为示例，并非真实的资源
                    success: (res) => {
                        if (res.statusCode === 200) {
                            console.log('downloadFile', res)
                            console.log('下载成功');
                            let filePath = res.tempFilePath
                            uni.saveImageToPhotosAlbum({
                                filePath,
                                success: (res) => {
                                    uni.showToast({
                                        title: '下载成功',
                                        icon: 'success',
                                    })
                                    setTimeout(function () {
                                        uni.hideLoading();
                                    }, 1000);
                                    let fileMgr = wx.getFileSystemManager();
                                    // 删除本地文件
                                    fileMgr.unlink({
                                        filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.mp4',
                                        success: function (r) {
                                            console.log('unlink-getFileSystemManager')
                                            console.log(r)
                                        },
                                    })
                                },
                                complete(res) {
                                    console.log('saveVideoToPhotosAlbum-complete')
                                    console.log(res)
                                }
                            })
                        }
                    }
                });
            });
        },
        //上传图片到腾讯云
        uploadFileToTencentClound(filename, filePath) {
            return new Promise((resolve, reject) => {
                cos.postObject({
                    Bucket: 'ztapp-1304966785',
                    Region: 'ap-nanjing',
                    Key: this.user.openid + '/' + filename,
                    FilePath: filePath,
                    onProgress: function (info) {
                        console.log("[cos.postObject-seccess]", JSON.stringify(info));
                    }
                },
                    function (err, data) {
                        console.log("[cos.postObject-err]", err || data);
                        resolve(data.headers.location)
                    })
            })
        }

    }
}

</script>

<style lang='scss' scoped>
@import "@/uni_modules/uview-ui/theme.scss";
$all_width: 96rpx;
$all_height: 96rpx;

.movable-area {
    height: 100vh;
    width: 750rpx;
    top: 0;
    position: fixed;
    pointer-events: none; //此处要加，鼠标事件可以渗透

    .movable-view {
        width: $all_width;
        height: $all_height;
        pointer-events: auto; //恢复鼠标事件

        image {
            width: $all_width;
            height: $all_height;
        }
    }
}
</style>